/**
 * Created by nengjian on 2017/4/17.
 * Based on pipeline.js from when.js:
 * https://github.com/cujojs/when/blob/3.7.4/pipeline.js
 */
var Promise = require('bluebird');

function pipeline(tasks /* initial arguments */) {
    var args = slice = Array.prototype.slice,

        runTask = function (args, task) {
            runTask = function (arg, task) {
                return task(arg);
            };
            
            return task.apply(null, args);
        };

    // Resolve any promises for the arguments passed in first
    return Promise.all(slice.call(arguments, 1)).then(function (args) {
        // Iterate through the tasks passing args from one into the next
        return Promise.reduce(tasks, function (arg, task) {
            return runTask(arg, task);
        }, args);
    });
}

module.exports = pipeline;
